//
//  MXAddSuccessController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/3.
//

#import "MXAddSuccessController.h"
#import "MxPublicNav.h"
#import "MXAddRenameController.h"
#import <UINavigationController+FDFullscreenPopGesture.h>

@interface MXAddSuccessController () <MxNavigationViewDelegate>
@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic, strong) UILabel *nextLab;

@property (nonatomic, strong) UILabel *titleLab;

@property (nonatomic,strong) UILabel * descLab;

@property (nonatomic,assign) NSInteger detectionCount;//检测次数
@property (nonatomic,assign) NSInteger deviceStatus;//0 检测中 1 成功 2失败
@property (nonatomic,assign) NSInteger deviceStatus0;

@property (nonatomic,strong) NSString * deviceId;//后台记录的deviceId

@end

@implementation MXAddSuccessController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createUI];
}

- (void)createUI {
    
    self.fd_interactivePopDisabled = YES;
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.backButton.hidden = YES;
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    
    UILabel *addLab = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.nav.frame) + kScalHeight(66), kScreenW, 30)];
    addLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:addLab];
    addLab.text = @"设备配置信息检测中";
    addLab.textColor = [UIColor colorWithHexString:@"#221815"];
    addLab.font = PFRFontMedium(30);
    self.titleLab = addLab;
    
    
    self.descLab = [[UILabel alloc] init];
    self.descLab.textColor = [UIColor redColor];
    self.descLab.text = @"1、请检查WIFI密码是否正确\n2、请将设备靠近WIFI";
    self.descLab.font = PFRFont(14);
    self.descLab.textAlignment = NSTextAlignmentCenter;
    self.descLab.numberOfLines = 0;
    self.descLab.hidden = YES;
    [self.view addSubview:self.descLab];
    [self.descLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addLab.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    UIImageView *placeImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add_success_icon"]];
    [self.view addSubview:placeImageV];
    [placeImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(151);
        make.height.mas_equalTo(290);
        make.top.mas_equalTo(addLab.mas_bottom).offset(kScalHeight(97));
        make.centerX.mas_equalTo(self.view);
    }];
    
    MJWeakSelf
    self.nextLab = [[UILabel alloc] init];
    [self.view addSubview:self.nextLab];
    self.nextLab.backgroundColor = [UIColor dc_colorWithHexString:DC_999999];//[UIColor colorWithHexString:@"#3278F6"];
    self.nextLab.userInteractionEnabled = YES;
    self.nextLab.textColor = [UIColor whiteColor];
    self.nextLab.text = @"下一步";
    self.nextLab.font = PFRFontMedium(16);
    self.nextLab.textAlignment = NSTextAlignmentCenter;
    self.nextLab.layer.cornerRadius = 24;
    self.nextLab.layer.masksToBounds = YES;
    [self.nextLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf nextStep];
    }]];
    
    [self.nextLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.height.mas_equalTo(48);
        make.bottom.offset(-50);
    }];
    
    [self reloadLab];
    [self detectionDeviceInfo];
}

- (void)nextStep {
    if(self.deviceStatus != 1){
        return;
    }
    NSMutableArray * arr = [NSMutableArray array];
    for (id obj in self.navigationController.viewControllers) {
        NSLog(@"====nextStep:%@",[obj class]);
        [arr addObject:obj];
        if([obj isKindOfClass:NSClassFromString(@"MXAddEquipmentController")]){
            break;
        }
    }
    MXAddRenameController *renameVc = [[MXAddRenameController alloc] init];
    renameVc.familyId = self.familyId;
    renameVc.deviceId = self.deviceId;
    [arr addObject:renameVc];
    [self.navigationController setViewControllers:arr animated:YES];
}

- (void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

-(void)reloadLab{
    if(self.deviceStatus != 0){
        return;
    }
    self.deviceStatus0++;
    self.deviceStatus0 = self.deviceStatus0%4;
    if(self.deviceStatus0 == 0){
        self.titleLab.text = @"配网状态检测中";
    }else if(self.deviceStatus0 == 1){
        self.titleLab.text = @"配网状态检测中.";
    }else if(self.deviceStatus0 == 2){
        self.titleLab.text = @"配网状态检测中..";
    }else if(self.deviceStatus0 == 3){
        self.titleLab.text = @"配网状态检测中...";
    }
    
    MJWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf reloadLab];
    });
}

-(void)detectionDeviceInfo{
    if(self.detectionCount > 13){
        NSLog(@"===失败");
        self.deviceStatus = 2;
        self.titleLab.text = @"配网失败";
        self.nav.backButton.hidden = NO;
        self.fd_interactivePopDisabled = NO;
        self.descLab.hidden = NO;
        return;
    }
    self.detectionCount++;
    NSLog(@"===开始第 %ld 次检查...",(long)self.detectionCount);
    MJWeakSelf;
    NSDictionary *param = @{@"deviceName":self.deviceName?self.deviceName:@""};
    [[DCHttpClient shareClient] requestWithPath:@"api/app/device/describeDevice" params:param httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            NSLog(@"===%@",dict);
            weakSelf.deviceId = dict[@"data"][@"deviceId"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"deviceId"]] : @"";
            NSInteger activateStatus = dict[@"data"][@"activateStatus"] ? [dict[@"data"][@"activateStatus"] integerValue] : 0;
            if(activateStatus == 1){
                weakSelf.deviceStatus = 1;
                weakSelf.titleLab.text = @"配网成功";
                weakSelf.nextLab.backgroundColor = [UIColor colorWithHexString:@"#3278F6"];
            }else{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf detectionDeviceInfo];
                });
            }
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf detectionDeviceInfo];
            });
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf detectionDeviceInfo];
        });
    }];
}

@end
